import base64
import json
import logging
import os
import sys
import time
from contextlib import contextmanager
from datetime import datetime, timedelta
from typing import Dict, Optional, Union, Tuple, Any
from typing import List
from deepdiff import DeepDiff

import polars as pl
import psycopg2
import psycopg2.extras
import psycopg2.pool
import requests
import rsa

import time
from typing import Optional, Dict, Union
import time
from datetime import datetime, timedelta
from typing import Optional, Dict, Union

import requests



def _call_api_with_retry(
        api_url: str,
        token_params: Optional[dict] = None,
        api_params: Optional[dict] = None,
        headers: Optional[Dict[str, str]] = None,
        timeout: int = 10,
        retry_times: int = 3,
) -> Union[requests.Response, None]:
    for attempt in range(retry_times + 1):
        response = requests.post(url=api_url, data=token_params, json=api_params, headers=headers, timeout=timeout)
        return response
    return None

def _generate_token( params: Optional[dict] = None) -> str:
    try:
        message = params['username'] + ";" + datetime.now().strftime("%Y-%m-%d") + ";" + params['password']
        public_key_rsa = rsa.PublicKey.load_pkcs1(params['public_key'])
        crypto = rsa.encrypt(message.encode("utf-8"), public_key_rsa)
        crypto64 = base64.b64encode(crypto)
        request_params = {'json': crypto64}
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.3"
        }
        # todo
        print(request_params)
        token = _call_api_with_retry(api_url = params['auth_url'], token_params=request_params, headers=headers,)
        return token
    except Exception as e:
        raise Exception(f"获取 token 失败: {e}")

api_config = {
    'batch_config': {
        'batch_size': 1000,  # 每批次处理的记录数
        'max_workers': 4  # 并发处理线程数
    },
    'api_params': {
        'ETL_DATE': (datetime.now() - timedelta(days=100)).strftime("%Y-%m-%d %H:%M:%S"),
        'pageSize': 10,
        'pageNo': 1
    },
    'token_param': {
        'auth_url': 'http://u.95579.com/dataapi/auth',
        'username': "thfund@cjsc.com.cn",
        'password': "dt7mTNwA",
        'public_key': """
                                  -----BEGIN RSA PUBLIC KEY-----
                                  MIGJAoGBAJDhq0rhTN2YeAICdi5Zpl2sqQTCDXGCrCxY9gx1Jb4+etCZkfy/0PZQ
                                  ZHA7TBmrbert4PUZKbpy0qEYnxvWGGmZ/cJ0YYSgue2aPSfkq/QRS/Y58W+j+TcO
                                  lCv+dZ7Wi0k68Yu7wyH+ZbDo55ySwLpiI/o+IQvzOwRPHlQ0yIkVAgMBAAE=
                                  -----END RSA PUBLIC KEY-----
                                  """
    },
    'api_url': 'http://u.95579.com/dataapi/get_alp_api_data_info',
}

config_env = 'standalone'

token = _generate_token(params=api_config['token_param'])
print(token)
